package com.xywh.micro_warehousing.mvp.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xywh.micro_warehousing.R;
import com.xywh.micro_warehousing.di.component.DaggerTab2Component;
import com.xywh.micro_warehousing.di.module.Tab2Module;
import com.xywh.micro_warehousing.mvp.contract.Tab2Contract;
import com.xywh.micro_warehousing.mvp.presenter.Tab2Presenter;
import com.xywh.micro_warehousing.mvp.ui.activity.ScanActivity;
import com.xywh.micro_warehousing.mvp.ui.adapter.Tab2ShenQingYuLiuLieBiaoAdapter;
import com.xywh.micro_warehousing.mvp.ui.adapter.Tab2WuLiaoLieBiaoAdapter;
import com.xywh.micro_warehousing.mvp.ui.entity.Material;
import com.xywh.micro_warehousing.mvp.ui.entity.OpenDoor;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;

import static android.support.v7.widget.DividerItemDecoration.VERTICAL;
import static com.jess.arms.base.BaseConstants.SCAN_REQUEST_CODE;
import static com.jess.arms.utils.Preconditions.checkNotNull;


public class Tab2Fragment extends BaseFragment<Tab2Presenter> implements Tab2Contract.View, OnRefreshListener {


    public static final int REQUEST_WU_LIAO = 101;
    private static boolean mIsNeedDemo = true;
    @BindView(R.id.empty_text)
    TextView empty_text;
    @BindView(R.id.empty_image)
    ImageView empty_image;
    @BindView(R.id.empty)
    View mEmptyLayout;
    @BindView(R.id.recyclerViewWuLiaoLieBiao)
    RecyclerView mRecyclerViewWuLiaoLieBiao;
    @BindView(R.id.recyclerViewShenQingYuLiuLieBiao)
    RecyclerView mRecyclerViewShenQingYuLiuLieBiao;
    @BindView(R.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.btn_yi_jian_kai_suo)
    Button btnYiJianKaiSuo;
    Unbinder unbinder;
    @BindView(R.id.tv_cang_wei_hao)
    TextView tvCangWeiHao;
    @BindView(R.id.tv_zhuang_tai)
    TextView tvZhuangTai;
    private Tab2WuLiaoLieBiaoAdapter mTab2WuLiaoLieBiaoAdapter;
    private Tab2ShenQingYuLiuLieBiaoAdapter mTab2ShenQingYuLiuLieBiaoAdapter;
    private List<Material.DataBean> mDataBeanList = new ArrayList<>();
    private String mCangWeiID; //仓位id
    private String mGuiZiId; //柜子id
    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;

    public static Tab2Fragment newInstance() {
        Tab2Fragment fragment = new Tab2Fragment();
        return fragment;
    }

    @Subscriber(tag = "updateDingWeiDiZhi2", mode = ThreadMode.MAIN)
    public void updateDingWeiDiZhi2(String address) {
        if (!TextUtils.isEmpty(address))
            tvLocation.setText("当前地址：" + address);

    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerTab2Component //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .tab2Module(new Tab2Module(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tab2, container, false);
        initToolbar(view);
        return view;
    }

    private void initToolbar(View view) {
//        ToolbarUtils.initToolbarTitleNoBack(view, this, "一键扫码");
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        initRefreshLayout();
        initEmpty();
        initRecyclerViewWuLiaoLieBiao();
        initRecyclerViewShenQingYuLiuLie();
        //getTab2Data();
    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new
                ClassicsHeader(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.autoRefresh();
        mRefreshLayout.setEnableLoadMore(false);
    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("请扫描柜子二维码，查看柜子库存信息或预留信息。");
    }

    private void initRecyclerViewWuLiaoLieBiao() {
        mRecyclerViewWuLiaoLieBiao.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerViewWuLiaoLieBiao.addItemDecoration(new DividerItemDecoration(getActivity(), VERTICAL));
        mRecyclerViewWuLiaoLieBiao.setItemAnimator(new DefaultItemAnimator());
        mRecyclerViewWuLiaoLieBiao.setAdapter(mTab2WuLiaoLieBiaoAdapter = new Tab2WuLiaoLieBiaoAdapter(getActivity(), mDataBeanList));

        mTab2WuLiaoLieBiaoAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                Utils.navigation(getActivity(), RouterHub.SALES_CLIENT_ZUI_XIN_XIAO_XI_XIANG_QING_ACTIVITY);
            }
        });
    }

    private void initRecyclerViewShenQingYuLiuLie() {
        mRecyclerViewShenQingYuLiuLieBiao.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerViewShenQingYuLiuLieBiao.addItemDecoration(new DividerItemDecoration(getActivity(), VERTICAL));
        mRecyclerViewShenQingYuLiuLieBiao.setItemAnimator(new DefaultItemAnimator());
        mRecyclerViewShenQingYuLiuLieBiao.setAdapter(mTab2ShenQingYuLiuLieBiaoAdapter = new Tab2ShenQingYuLiuLieBiaoAdapter(getActivity(), mDataBeanList));

        mTab2ShenQingYuLiuLieBiaoAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                Utils.navigation(getActivity(), RouterHub.SALES_CLIENT_ZUI_XIN_XIAO_XI_XIANG_QING_ACTIVITY);
            }
        });
    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)}
     * 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     *
     * <p>
     * Example usage:
     *
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Subscriber(tag = "toScan", mode = ThreadMode.MAIN)
    public void toScan1(String value) {
        toScan();
    }

    private void toScan() {
        Intent newIntent = new Intent(getActivity(), ScanActivity.class);
        mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, REQUEST_WU_LIAO);
        startActivityForResult(newIntent, REQUEST_WU_LIAO);
    }

    @Subscriber(tag = "setYiJianKaiSuoXianShi", mode = ThreadMode.MAIN)
    public void setYiJianKaiSuoXianShi(String scan_result) {


        if (scan_result.contains("-")) { //如果没有-说明是扫描的是柜子二维码，如果有-说明是扫描的柜子里面的仓位二维码，则显示预留的物料数据
            tvCangWeiHao.setText("柜子编码：" + scan_result.split("-")[0] + ",仓位号：" + scan_result.split("-")[1]);
            mCangWeiID = scan_result;
            btnYiJianKaiSuo.setVisibility(View.VISIBLE);
            mRecyclerViewWuLiaoLieBiao.setVisibility(View.GONE);
            mRecyclerViewShenQingYuLiuLieBiao.setVisibility(View.VISIBLE);
        } else {
            tvCangWeiHao.setText("柜子编码：" + scan_result);
            mGuiZiId = scan_result;
            btnYiJianKaiSuo.setVisibility(View.GONE); //隐藏一键开锁功能
            mRecyclerViewWuLiaoLieBiao.setVisibility(View.VISIBLE);
            mRecyclerViewShenQingYuLiuLieBiao.setVisibility(View.GONE);
            mDataBeanList.clear();
            mTab2ShenQingYuLiuLieBiaoAdapter.notifyDataSetChanged();
            mTab2WuLiaoLieBiaoAdapter.notifyDataSetChanged();
            getTab2Data(mGuiZiId);

        }

    }

    private void getTab2Data(String counterNo) {
        HashMap<String, String> map = new HashMap<>();
        map.put("counterNo", counterNo);
        mPresenter.getTab2Data(map);
    }

    @Override
    public void getTab2DataSuccess(Material entityData) {
//200 预留的列表  201  柜子里面所有物料
        if (entityData != null) {
//            tvLocation.setText("当前仓库：" + entityData.getStorename());

            if (entityData.getCode() == 200) {
                tvZhuangTai.setText("您预留的物料列表：");

                mRecyclerViewWuLiaoLieBiao.setVisibility(View.GONE);

                if (entityData.getData() != null && entityData.getData().size() > 0) {

                    mDataBeanList.clear();
                    mDataBeanList.addAll(entityData.getData());
                    mTab2ShenQingYuLiuLieBiaoAdapter.notifyDataSetChanged();
                    mEmptyLayout.setVisibility(View.GONE);
                    mRecyclerViewShenQingYuLiuLieBiao.setVisibility(View.VISIBLE);
                    btnYiJianKaiSuo.setVisibility(View.VISIBLE);//显示一键开锁功能

                } else {
                    mEmptyLayout.setVisibility(View.VISIBLE);
                    mRecyclerViewShenQingYuLiuLieBiao.setVisibility(View.GONE);
                    btnYiJianKaiSuo.setVisibility(View.GONE); //隐藏一键开锁功能

                }
            }


            if (entityData.getCode() == 201) {
                tvZhuangTai.setText("柜子中所有的物料列表：");

                mRecyclerViewShenQingYuLiuLieBiao.setVisibility(View.GONE);

                if (entityData.getData() != null && entityData.getData().size() > 0) {

                    mDataBeanList.clear();
                    mDataBeanList.addAll(entityData.getData());
                    mTab2WuLiaoLieBiaoAdapter.notifyDataSetChanged();
                    mEmptyLayout.setVisibility(View.GONE);
                    mRecyclerViewWuLiaoLieBiao.setVisibility(View.VISIBLE);
                    btnYiJianKaiSuo.setVisibility(View.GONE); //隐藏一键开锁功能

                } else {
                    mEmptyLayout.setVisibility(View.VISIBLE);
                    mRecyclerViewWuLiaoLieBiao.setVisibility(View.GONE);
                    btnYiJianKaiSuo.setVisibility(View.GONE); //隐藏一键开锁功能


                }
            }

            if (entityData.getCode() == 400) { //仓储柜已停用
                showMessage(entityData.getMessage());
            }
        }
    }

    @Override
    public void getScanMaterialAPISuccess(Material entityData) {
        if (entityData != null) {
//            tvLocation.setText("当前仓库：" + entityData.getStorename());
//
//            if (entityData.getList() != null && entityData.getList().size() > 0) {
//                for (int i = 0; i < entityData.getList().size(); i++) {
//                    entityData.getList().get(i).setSpname(entityData.getSpname());
//                }
//                mDataBeanList.clear();
//                mDataBeanList.addAll(entityData.getList());
//                mTab2WuLiaoLieBiaoAdapter.notifyDataSetChanged();
//                mEmptyLayout.setVisibility(View.GONE);
//                mRecyclerViewWuLiaoLieBiao.setVisibility(View.VISIBLE);
//            } else {
//                mEmptyLayout.setVisibility(View.VISIBLE);
//                mRecyclerViewWuLiaoLieBiao.setVisibility(View.GONE);
//            }
        }

    }

    @Override
    public void openDoorSuccess(OpenDoor entityData) {
        if (entityData.getCode() == 200) {
            showMessage("开锁成功");
//            Utils.navigation(getActivity(), RouterHub.ACTIVITY_UNLOCKED_SUCCESSFULLY);


            TimerTask task = new TimerTask() {
                @Override
                public void run() {

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            btnYiJianKaiSuo.setVisibility(View.GONE); //隐藏一键开锁功能
                            mDataBeanList.clear();
                            mTab2ShenQingYuLiuLieBiaoAdapter.notifyDataSetChanged();
                            mTab2WuLiaoLieBiaoAdapter.notifyDataSetChanged();
                            getTab2Data(mGuiZiId);
                        }
                    });

                }
            };
            Timer timer = new Timer();
            timer.schedule(task, 5000);//3秒后执行TimeTask的run方法

        } else if (entityData.getCode() == 400) { //仓储柜已停用
            showMessage(entityData.getMessage());
        } else {
            showMessage("开锁失败");
        }

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

//        mRefreshLayout.finishRefresh();
//        mEmptyLayout.setVisibility(View.GONE);

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        try {
            checkNotNull(message);
            ArmsUtils.makeText(getActivity(), message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == REQUEST_WU_LIAO) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                //http://dzaudit.xywuhe.com/opencontainer.aspx?spid=11
                mCangWeiID = extras.getString(BaseConstants.SCAN_RESULT);

                if (mCangWeiID.contains("http")) {
                    mCangWeiID = mCangWeiID.substring(mCangWeiID.lastIndexOf("=") + 1);
                }


                EventBus.getDefault().post(mCangWeiID, "xetContainerNumber");

//                mPresenter.validateReturnInstore(this, mid);
//                showMessage("扫描的数据是：" + spid);
                getScanMaterialAPI(mCangWeiID);
            }

        }
    }

    private void getScanMaterialAPI(String spid) {
//        HashMap<String, String> map = new HashMap<>();
//        map.put("spid", spid);
        mPresenter.getScanMaterialAPI(spid);
    }


    @OnClick(R.id.btn_yi_jian_kai_suo)
    public void onViewClicked() {
        showMessageNegativeDialogYiJianKaiMen();
    }

    private void showMessageNegativeDialogYiJianKaiMen() {
        new QMUIDialog.MessageDialogBuilder(getContext())
                .setTitle("确认一键开门")
                .setMessage("确认一键开门领取物料？")
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, "确定", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {

                        if (mDataBeanList != null && mDataBeanList.size() > 0) {
                            for (int i = 0; i < mDataBeanList.size(); i++) {
                                HashMap<String, String> map = new HashMap<>();
                                map.put("spid", String.valueOf(mDataBeanList.get(i).getCounterId()));
                                map.put("mid", String.valueOf(mDataBeanList.get(i).getMId()));
                                map.put("uid", mSharedPreferencesHelper.getString(BaseConstants.UID));
                                mPresenter.openDoor(map);
                            }
                        }
                        dialog.dismiss();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    @Subscriber(tag = "kaiMen", mode = ThreadMode.MAIN)
    public void kaiMen(Material.DataBean dataBean) {
        showMessageNegativeDialog(dataBean);
    }

    private void showMessageNegativeDialog(Material.DataBean dataBean) {
        new QMUIDialog.MessageDialogBuilder(getContext())
                .setTitle("确认开门")
                .setMessage("确认开门领取物料？")
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, "确定", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        HashMap<String, String> map = new HashMap<>();
                        map.put("spid", String.valueOf(dataBean.getCounterId()));
                        map.put("mid", String.valueOf(dataBean.getMId()));
                        map.put("uid", mSharedPreferencesHelper.getString(BaseConstants.UID));
                        mPresenter.openDoor(map);
                        dialog.dismiss();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }
}
